package com.seckill.controller;

import com.seckill.common.CommonResponse;
import com.seckill.common.error.BusinessError;
import com.seckill.common.error.BusinessException;
import com.seckill.common.error.CommonError;
import com.seckill.common.error.UserError;
import com.seckill.controller.viewobject.UserVO;
import com.seckill.service.UserService;
import com.seckill.service.model.UserModel;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@Controller("user")
@RequestMapping("/user")
@CrossOrigin // 解决跨域问题 CORS policy
public class UserController extends BaseController {

    @Autowired
    private UserService userService;

    @Autowired
    private HttpServletRequest request;

    /**
     * 用户获取动态短信验证码（OTP）
     *
     * @param telephone 手机号
     * @return
     */
    @RequestMapping(value = "/getotp",method = {RequestMethod.POST},consumes = {CONTENT_TYPE_FORMED})
    @ResponseBody
    public CommonResponse getOtp(@RequestParam(name = "telephone") String telephone) {
        // 生成码
        Random random = new Random();
        int randomInt = random.nextInt(99999);
        randomInt += 10000;
        String otpCode = String.valueOf(randomInt);

        // 关联码和手机号，key-value形式通常采用redis存储,可以反复覆盖
        // 1 使用httpsession绑定手机号与码
        request.getSession().setAttribute(telephone, otpCode);

        // 将码通过短信发送给客户--省略，需要购买第三方短信通道
        System.out.println("telephone = " + telephone +", otpcode = " + otpCode);

        return CommonResponse.create(null);
    }

    /**
     * 根据id获取用户信息
     *
     * @param id 用户id
     * @return
     */
    @RequestMapping("/get")
    @ResponseBody
    public CommonResponse getUser(@RequestParam(name = "id") Integer id) throws BusinessException {
        // 调用service服务获取对应id的用户对象并返回给前端
        UserModel userModel = userService.getUserById(id);

        if (userModel == null) {
            throw new BusinessException(UserError.USER_NOT_EXIST);
        }

        // 将核心领域模型用户对象转化为可供UI使用的viewObject
        UserVO userVO = convertFromModel(userModel);
        return CommonResponse.create(userVO);
    }

    private UserVO convertFromModel(UserModel userModel) {
        if (userModel == null) {
            return null;
        }
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(userModel, userVO);
        return userVO;
    }
}
